package com.ruoyi.ghxx.controller;

import java.io.File;
import java.io.InputStream;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import com.alibaba.fastjson2.JSON;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.ghxx.aop.SysInitData;
import com.ruoyi.ghxx.aop.SysInitUpdateData;
import com.ruoyi.ghxx.aop.SysQueryData;
import com.ruoyi.ghxx.util.Detect;
import com.ruoyi.ghxx.util.ImageUtils;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import javax.servlet.http.HttpServletResponse;
import com.ruoyi.ghxx.domain.BEchartZt;
import com.ruoyi.ghxx.service.IBEchartZtService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 大屏管理Controller
 * 
 * @author ruoyi
 * @date 2023-05-24
 */
@RestController
@RequestMapping("/ghxx/bEchartZt")
public class BEchartZtController extends BaseController
{
    @Autowired
    private IBEchartZtService bEchartZtService;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    /**
     * 查询大屏管理列表
     */
    @PreAuthorize("@ss.hasPermi('ghxx:bEchartZt:list')")
    @GetMapping("/list")
    @SysQueryData
    public TableDataInfo list(BEchartZt bEchartZt)
    {
        startPage();
        List<BEchartZt> list = bEchartZtService.selectBEchartZtList(bEchartZt);
        return getDataTable(list);
    }

    /**
     * 导出大屏管理列表
     */
    @PreAuthorize("@ss.hasPermi('ghxx:bEchartZt:export')")
    @Log(title = "大屏管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, BEchartZt bEchartZt)
    {
        List<BEchartZt> list = bEchartZtService.selectBEchartZtList(bEchartZt);
        ExcelUtil<BEchartZt> util = new ExcelUtil<BEchartZt>(BEchartZt.class);
        util.exportExcel(response, list, "大屏管理数据");
    }

    /**
     * 获取大屏管理详细信息
     */
    @PreAuthorize("@ss.hasPermi('ghxx:bEchartZt:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(bEchartZtService.selectBEchartZtById(id));
    }

    /**
     * 新增大屏管理
     */
    @PreAuthorize("@ss.hasPermi('ghxx:bEchartZt:add')")
    @Log(title = "大屏管理", businessType = BusinessType.INSERT)
    @PostMapping
    @SysInitData
    public AjaxResult add(@RequestBody BEchartZt bEchartZt)
    {
        return toAjax(bEchartZtService.insertBEchartZt(bEchartZt));
    }

    /**
     * 修改大屏管理
     */
    @PreAuthorize("@ss.hasPermi('ghxx:bEchartZt:edit')")
    @Log(title = "大屏管理", businessType = BusinessType.UPDATE)
    @PutMapping
    @SysInitUpdateData
    public AjaxResult edit(@RequestBody BEchartZt bEchartZt)
    {
        return toAjax(bEchartZtService.updateBEchartZt(bEchartZt));
    }

    /**
     * 删除大屏管理
     */
    @PreAuthorize("@ss.hasPermi('ghxx:bEchartZt:remove')")
    @Log(title = "大屏管理", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(bEchartZtService.deleteBEchartZtByIds(ids));
    }

    @GetMapping("/getZtData")
    @SysQueryData
    public AjaxResult getZtData(BEchartZt bEchartZt)
    {
        if(Detect.isEmpty(bEchartZt.getGuid())){
            return AjaxResult.error("系统中无此组态界面！");
        }
        BeanPropertyRowMapper<BEchartZt> bDeviceDetailMapper = new BeanPropertyRowMapper<>(BEchartZt.class);
        String sql="select page_name,page_data from b_echart_zt where guid=? ";
        try {
            bEchartZt = jdbcTemplate.queryForObject(sql, bDeviceDetailMapper,bEchartZt.getGuid());//处理结果集EmptyResultDataAccessException，不做任何操作
        }catch (EmptyResultDataAccessException e){
        }
        return AjaxResult.success(bEchartZt);
    }
    /*
     * 保存组态信息
     * */
    @PostMapping(value = "/saveZt")
    @SysInitData
    public AjaxResult saveZt(@RequestBody BEchartZt bEchartZt)
    {
        if(Detect.isEmpty(bEchartZt.getGuid())){
            return AjaxResult.error("参数不符合规定");
        }
        BEchartZt bEchartZtQuery=new BEchartZt();
        bEchartZtQuery.setGuid(bEchartZt.getGuid());
        List<BEchartZt> bEchartZts = bEchartZtService.selectBEchartZtList(bEchartZtQuery);
        if(bEchartZts.size()>0){
            BEchartZt echartZt = bEchartZts.get(0);
            echartZt.setPageData(bEchartZt.getPageData());
            bEchartZtService.updateBEchartZt(echartZt);
        }else{
            bEchartZtService.insertBEchartZt(bEchartZt);
        }
        return AjaxResult.success();
    }
    /*
     * 复制组态信息
     * */
    @PostMapping(value = "/copyZtData")
    @SysInitData
    public AjaxResult copyZtData(@RequestBody BEchartZt bEchartZt)
    {
        String ztData=bEchartZt.getPageData();
        String guid=UUID.randomUUID().toString();
        bEchartZt.setId(null);
        bEchartZt.setGuid(guid);
        bEchartZt.setPageName(bEchartZt.getPageName()+"_副本");
        bEchartZt.setPageData(ztData);
        bEchartZtService.insertBEchartZt(bEchartZt);
        return AjaxResult.success();
    }
    @PostMapping("/importZtJson")
    public AjaxResult importZtJson(@RequestBody MultipartFile file, String deviceImei, String guid) throws Exception{
        InputStream inputStream = file.getInputStream();
        if(file.isEmpty()){
            return AjaxResult.error("无效的配置文件");
        }
        if(file.getOriginalFilename().indexOf("json")==-1){
            return AjaxResult.error("无效的配置文件");
        }
        BEchartZt bEchartZt=new BEchartZt();
        try {
            bEchartZt = JSON.parseObject(inputStream, BEchartZt.class);
        }catch (Exception e){
            return AjaxResult.error("无效的配置文件");
        }finally {
            inputStream.close();
        }
        String ztData=bEchartZt.getPageData();
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if(Detect.isEmpty(guid)){
            guid=UUID.randomUUID().toString();
            bEchartZt.setId(null);
            bEchartZt.setGuid(guid);
            bEchartZt.setPageData(ztData);
            String deptIds=","+loginUser.getUser().getDept().getAncestors()+","+loginUser.getUser().getDeptId()+",";
            bEchartZt.setDeptIdStrs(deptIds);
            bEchartZt.setCreateBy(loginUser.getUsername());
            bEchartZt.setCreateTime(new Date());
            bEchartZt.setUpdateBy(loginUser.getUsername());
            bEchartZt.setUpdateTime(new Date());
        }else {
            BEchartZt bDeviceZtQuery=new BEchartZt();
            bDeviceZtQuery.setGuid(guid);
            List<BEchartZt> bDeviceZts = bEchartZtService.selectBEchartZtList(bDeviceZtQuery);
            if(bDeviceZts.size()>0){
                bDeviceZtQuery=bDeviceZts.get(0);
            }
            bDeviceZtQuery.setPageData(ztData);
            bEchartZtService.updateBEchartZt(bDeviceZtQuery);
        }
        return AjaxResult.success("导入成功");
    }
    /*
     * 保存组态信息
     * */
    @PostMapping(value = "saveZtImage")
    public AjaxResult saveZtImage(@RequestBody BEchartZt bEchartZt)
    {
        if(Detect.isEmpty(bEchartZt.getGuid())){
            return AjaxResult.error("参数不符合规定");
        }
        MultipartFile image =ImageUtils.base64ToMultipartFile(bEchartZt.getBase64());
        String imageUrl="";
        try{
            imageUrl = FileUploadUtils.upload(RuoYiConfig.getAvatarPath(), image);
        }catch (Exception e){
            return AjaxResult.error(500,"上传组件异常，"+e.toString());
        }
        BEchartZt bDeviceZtQuery=new BEchartZt();
        bDeviceZtQuery.setGuid(bEchartZt.getGuid());
        List<BEchartZt> bDeviceZts = bEchartZtService.selectBEchartZtList(bDeviceZtQuery);
        if(bDeviceZts.size()>0){
            bEchartZt = bDeviceZts.get(0);
            if(Detect.notEmpty(bEchartZt.getPageImage())){
                String newUrl = bEchartZt.getPageImage().replace("/profile", "").replace("/avatar", "");
                File fileQuery=new File(RuoYiConfig.getAvatarPath()+newUrl);
                if(fileQuery.exists()){
                    System.out.println("删除之前的图片资源");
                    fileQuery.delete();
                }
            }
            bEchartZt.setPageImage(imageUrl);
            bEchartZtService.updateBEchartZt(bEchartZt);
        }
        return AjaxResult.success();
    }
}
